"ui";

let S_DY = require('./Script_Dy/Script_Dy_Main.js');

let BSCRIPT = require('./Script_Base/Script_Base.js');
let { GetServerComand, SetCloseWb } = require('./ws.js');
let { EnumSysConf, UpDataUi, closeNtfOrder } = require('./Script_Base/Script_Base.js');

ui.layout(
    <frame >
        <vertical padding="15">
            <horizontal gravity='center'>
                <text text="----------版本号："></text>
                <text id="script_version" text=""></text>
                <text text="----------"></text>
            </horizontal>
            <horizontal>
                <text text="用户名："></text>
                <input id="username" w="*" hint="请输入用户名"></input>
            </horizontal>
            
            <horizontal>
                <text  text="卡  号："></text>
                <input id="password_card" w="*" hint="请输入卡号"></input>
            </horizontal>

            {/* <text gravity='center' text="----------刷视频脚本----------"></text>
            <text gravity='center' text="----------刷直播脚本----------"></text> */}
            <text gravity='center' text="----------关闭脚本：按音量减小键----------"></text>
            <button layout_gravity="bottom" h="auto" id="btn_saveConf" text="保存配置文件"/>
            <button layout_gravity="bottom" h="auto" id="btn_test" text="测试按钮"/>
            <text gravity='center' text="----------脚本信息----------"></text>
            <text id="script_info" text=""></text>
        </vertical>


    </frame >
);



ui.btn_test.click(function (){
    console.log("点击：测试按钮");
    threads.start(function () {
        // fUi.showFUi();
        console.log("进入测试线程");
        GetServerComand();
        // S_DY.main();
        // console.log(app.launchApp("抖音伏羲"));
        // console.log(app.launchPackage("io.virtualapp.sandvxposed"));
        // recents();
        // BSCRIPT.closeAppByRecents();


    });

});

ui.btn_saveConf.click(function (){
    console.log("点击：保存配置文件");
    
    threads.start(function () {
        // fUi.closeFUi();
        // LoadScritpFileEx("main.js");
        // closeNtfOrder();
        sleep(1000 * 8);
        BSCRIPT.OpenScreen();
    });
});

threads.start(function (){
    InitSlf();
    initConsole();

    // log('url=' + url);
    // log('filePath=' + filePath);
    // download(url, filePath);
}); 



//启用按键监听
events.observeKey();
//监听音量上键按下
events.onKeyDown("volume_down", function(event){
    SetCloseWb(false);
    engines.stopAll();
    console.log(new Date().Format('hh:mm:ss -> ') + "音量下键被按下了");  
    console.hide();
});




/**
 * 初始化自己
 */
function InitSlf() {

    UpDataUi();
    // ui.run(()=>{
    //     ui.username.setText(EnumSysConf.username);
    //     ui.password_card.setText(EnumSysConf.pw_card);
    //     ui.script_version.setText(EnumSysConf.version_latest_script);
    //     ui.script_info.setText("第一行\n第二行\n第三行\n第四行");
    // })
}











/**
 * 初始化控制台
 */
function initConsole(){
    console.show();
    console.setSize(device.width / 5 * 3, device.height / 3);
    console.setPosition(5, device.height / 3 * 2 - 50);
}

































/**
 * 下载脚本文件，脚本文件下载完成后将下载脚本文件的标识符设置成false
 * @param {*} fileName ：脚本文件名   /0.01/main.js
 */
function LoadScritpFileEx(fileName) {
    threads.start(function(){
        b_isUploadScriptFile = true;

        console.log(new Date().Format('hh:mm:ss -> ') + '开始下载脚本');
        // let url = EnumSlfConf.SERVER_ADDR + "/GetScriptFile/";
        // let url = "https://gitee.com/lkmudcfcu/fkfkwangzaide/blob/master/0.01/" + fileName;
        let url = "";

        // https://internal-api-drive-stream.feishu.cn/space/api/box/stream/download/all/boxcnMlukoSXQWLSstearcvmwif/?mount_node_token=doccnsT58uBIzjgG89atKT1Fl4f&mount_point=doc

        res = http.get(url);
        if (res.statusCode == 200) {
            let filePath = "/storage/emulated/0/tigerScript/" + fileName;
            // files.remove(filePath + fileName);
            console.log(filePath);
            sleep(10);
            // console.log(res.body.bytes());
            files.writeBytes(filePath, res.body.bytes());

            console.log(new Date().Format('hh:mm:ss -> ') + '脚本文件 ' + fileName + ' 下载完成。');
        } else {
            console.log(new Date().Format('hh:mm:ss -> ') + '脚本文件 ' + fileName + ' 下载脚本请求失败');
        }
        sleep(10);
        b_isUploadScriptFile = false;
    });
}




/**
 * @功能 悬浮窗显示文件下载进度
 */

var app下载地址 =
 'http://dy.fkapp.top/apps/script/libEx.js';
//  'https://gitee.com/lkmudcfcu/fkfkwangzaide/blob/master/0.01/main.js';

//https://web.feejii.com/755756c77c6e0ccda336cb622bdaac11/1678183796/files/2023/03/07/0/2796500/15967242264849195?filename=1.txt

// https://web.feejii.com/8dce1415daa3f552de8e7db16449b528/1678188281/files/2023/03/07/0/2796500/15967242264849195?filename=1.txt

// https://web.feejii.com/3a957d972d59a5f805597bfbbc5af94b/1678188278/files/2023/03/07/0/2796500/15971850090997927?filename=2.txt

// https://123-9-45-222.d.cjjd20.com:30443/123-557/22f53587/1814245128-0/22f53587660cbdd5dbd3a262057dce2d?v=2&t=1678276292&s=c28830f966a98d1d5ece7df3c31b3b96&filename=66.js&d=b7d09925

// https://123-4-21-79.d.cjjd20.com:30443/123-637/b2124f13/1814245128-0/b2124f1341c14a7779e514729d8bc27d?v=2&t=1678276331&s=baf131f9b4b6385fdfc74f075f6bdd44&filename=1.txt&d=946e1f1b

// https://115-62-58-53.d.cjjd20.com:30443/batch-download/123-637/b2124f13/1814245128-0/b2124f1341c14a7779e514729d8bc27d?v=2&t=1678276921&s=866b88c852dc2f9c33a9ab45f5bbc7ea&filename=1.txt&data=1814245128_true_944152569673983193_web&fromShare=1&d=d6860f8f

let url = app下载地址; // update_list.url
var filePath = files.join(files.getSdcardPath(), 'libEx.js');


function download(url, filePath) {
 importClass('java.io.FileOutputStream');
 importClass('java.io.IOException');
 importClass('java.io.InputStream');
 importClass('java.net.MalformedURLException');
 importClass('java.net.URL');
 importClass('java.net.URLConnection');
 importClass('java.util.ArrayList');

 var url = new URL(url);
 var conn = url.openConnection(); //URLConnection
 var inStream = conn.getInputStream(); //InputStream
 var fs = new FileOutputStream(filePath); //FileOutputStream
 var connLength = conn.getContentLength(); //int
 var buffer = util.java.array('byte', 1024); //byte[]
 var byteSum = 0; //总共读取的文件大小
 var byteRead; //每次读取的byte数
 log('要下载的文件大小=');
 log(connLength);
 var threadId = threads.start(function() {
     let nowDate = new Date();
   while (new Date() - nowDate < 1000 * 10) {
     var 当前写入的文件大小 = byteSum;
     var progress = (当前写入的文件大小 / connLength) * 100;
     if (progress > 0.1) {
       var progress = parseInt(progress).toString() + '%';
    //    ui.run(function() {
    //      w.progressNum.setText(progress);
    //    });
       if (当前写入的文件大小 >= connLength) {
         break;
       }
     }
     sleep(1000);
   }
 });
 while ((byteRead = inStream.read(buffer)) != -1) {
   byteSum += byteRead;
   //当前时间
   currentTime = java.lang.System.currentTimeMillis();
   fs.write(buffer, 0, byteRead); //读取
 }
 threadId && threadId.isAlive() && threadId.interrupt();
 toastLog('下载完成');
}

